package com.guoyihao.oj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.guoyihao.oj.common.ErrorCode;
import com.guoyihao.oj.exception.BusinessException;
import com.guoyihao.oj.judge.codesandbox.CodeSandBox;
import com.guoyihao.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.guoyihao.oj.judge.codesandbox.model.ExecuteCodeResponse;

/**
 * 远程代码沙箱（实际调用接口的沙箱）
 */
public class RemoteCodeSandBox implements CodeSandBox {

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        //原生代码沙箱请求
        //String url = "http://localhost:8090/executeCode";
        //Docker代码沙箱请求
        String url = "http://192.168.136.140:8090/executeCode";
        //将数据模型转换为Json数据
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        //再次发送Post请求调用代码沙箱
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(jsonStr)
                .execute()
                .body();
        if(StrUtil.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"代码沙箱请求失败,输出消息：" + responseStr);
        }
        return JSONUtil.toBean(responseStr,ExecuteCodeResponse.class);
    }
}
